<!-- eslint-disable vue/multi-word-component-names -->
<script setup>
import HomePanel from './HomePanel.vue'
//import { RouterLink } from 'vue-router'
import { ref, onMounted } from 'vue'

/*现在有后端了，用接口吧*/
const categoryshow1 = ref([]) // 用来存储获取的数据

// 异步获取数据
const fetchCategoryShow = async () => {
  try {
    const response = await fetch('http://localhost:8080/category/show') // 确保 URL 正确
    if (!response.ok) {
      // 如果响应状态码不是 2xx，会抛出错误
      throw new Error('Network response was not ok')
    }
    categoryshow1.value = await response.json() // 更新数据
    console.log('Fetched data:', categoryshow1.value) // 打印实际的数据
  } catch (error) {
    console.error('Failed to fetch category titles:', error)
    categoryshow1.value = [] // 如果发生错误，返回空数组
  }
}

// 使用 onMounted 在组件加载时调用 fetchCategoryTitle
onMounted(() => {
  fetchCategoryShow()
})

// 存储收藏夹和购物车的数据
const fav = ref([])
const cart = ref([])

// 添加到收藏夹
const addToFav = (good) => {
  console.log('Adding to favorites:', good)
  // 如果该商品不在收藏夹中，则添加，否则移除
  const index = fav.value.findIndex((item) => item.id === good.id)
  console.log('Favorite index:', index)
  if (index === -1) {
    fav.value.push(good)
    console.log('Added to favorites:', fav.value)
  } else {
    fav.value.splice(index, 1)
    console.log('Removed from favorites:', fav.value)
  }
}

// 添加到购物车
const addToCart = (good) => {
  console.log('Adding to cart:', good)
  const index = cart.value.findIndex((item) => item.id === good.id)
  console.log('Cart index:', index)
  console.log('Current cart contents:', cart.value)

  if (index === -1) {
    cart.value.push(good)
    console.log('Added to cart:', cart.value)
  } else {
    cart.value.splice(index, 1)
    console.log('Removed from cart:', cart.value)
  }
}


// 检查商品是否已被收藏
const isFav = (good) => {
  const result = fav.value.some((item) => item.id === good.id)
  console.log('Is in favorites:', result)
  return result
}

// 检查商品是否在购物车中
const isInCart = (good) => {
  const result = cart.value.some((item) => item.id === good.id)
  console.log('Is in cart:', result)
  return result
}
</script>
<template>
  <div class="show">
    <div class="home-container" v-for="item in categoryshow1" :key="item.id">
      <HomePanel :title="item.name" :sub-title="item.secCategory.map((cat) => cat.name).join(', ')">
        <ul class="goods-list">
          <li v-for="good in item.goods" :key="good.id">
            <RouterLink :to="`/goods/${good.id}`">
              <img :src="good.picture" alt="" />
              <p class="title">{{ good.name }}</p>
              <p class="alt">￥{{ good.price }}</p>
            </RouterLink>
            <div class="icon-container">
              <!-- 收藏按钮 -->
              <button
                type="button"
                class="icon"
                :class="{
                  'fav-active': isFav(good),
                  'fav-inactive': !isFav(good)
                }"
                @click="addToFav(good)"
              ></button>

              <!-- 购物车按钮 -->
              <button
                type="button"
                class="icon"
                :class="{
                  'cart-active': isInCart(good),
                  'cart-inactive': !isInCart(good)
                }"
                @click="addToCart(good)"
              ></button>
            </div>
          </li>
        </ul>
      </HomePanel>
    </div>
  </div>
</template>

<style lang="css">
.show {
  width: 100%;
  background-color: #fff;
  display: flex;
  flex-direction: column; /* 竖直方向排列 */
  align-items: center;
}
.home-container {
  width: 80%;
  margin-bottom: 30px;
}
.goods-list {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  gap: 20px; /* 商品之间的间距 */
  justify-content: flex-start; /* 居左对齐 */
  padding: 20px; /* 可以增加一些内边距使整体看起来更整齐 */
  height: 406px;

  li {
    width: 300px;
    height: 406px;
    position: relative; /* 确保图标容器的绝对定位相对于此父元素 */
    background: #f0f9f4;
    transition: all 0.5s;

    &:hover {
      transform: translate3d(0, -3px, 0);
      box-shadow: 0 3px 8px rgb(0 0 0 / 20%);
    }

    img {
      width: 306px;
      height: 306px;
    }

    p {
      font-size: 22px;
      padding-top: 12px;
      text-align: center;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }
}

.icon-container {
  position: absolute;
  bottom: 10px;
  right: 10px;
  display: flex;
  gap: 10px;
}

.icon {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  background-size: cover; /* 确保背景图填满按钮 */
  background-position: center; /* 背景图居中 */
  background-repeat: no-repeat; /* 不重复显示背景图 */
  cursor: pointer;
  transition: background-color 0.3s ease;
}

/* 收藏按钮的背景 */
.fav-inactive {
  background-image: url('@/assets/images/爱心.png');
}

.fav-active {
  background-image: url('@/assets/images/爱心1.png');
}

/* 购物车按钮的背景 */
.cart-inactive {
  background-image: url('@/assets/images/uncart.png');
}

.cart-active {
  background-image: url('@/assets/images/cart.png');
}
</style>
